package lzupdater.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import lzupdater.gui.listeners.LZFieldListener;
import lzupdater.gui.listeners.ProfileListener;
import lzupdater.utils.Profile;
import lzupdater.utils.WoWPathGuesser;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Action performed when the user click on the browse button to find the
 * LZProfiler.lua file
 * 
 * @author Fraskor
 */
public class BrowseAction extends AbstractAction implements ProfileListener {

	private String rosterFile = null;

	/**
	 * 
	 */
	private static final long serialVersionUID = 6482161557954108835L;
	private LZFieldListener fieldListener = null;

	public BrowseAction(LZFieldListener fieldListener) {
		this.fieldListener = fieldListener;
	}

	public void actionPerformed(ActionEvent arg0) {
		String startingPath = guessWoWPath();

		JFileChooser jfc = new JFileChooser(startingPath);

		FileFilter filter = new FileFilter() {

			@Override
			public boolean accept(File f) {
				return f.isDirectory() || f.getName().endsWith(".lua");
			}

			@Override
			public String getDescription() {
				return "Lua file";
			}

		};
		jfc.setFileFilter(filter);
		if (startingPath != null) {
			jfc.setSelectedFile(new File(startingPath));
		}
		int returnVal = jfc.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			String path = jfc.getSelectedFile().getAbsolutePath();
			fieldListener.setBrowseValue(path);
		}
	}

	public void setProfile(Profile profile) {
		if (profile != null) {
			rosterFile = profile.getRosterFile();
		} else {
			rosterFile = null;
		}
	}

	private String guessWoWPath() {
		if (rosterFile != null && new File(rosterFile).exists())
			return rosterFile;

		return WoWPathGuesser.getInstance().getLZProfilerBrowsePath(WoWPathGuesser.getInstance().getRootPath());		
 	}

}
